<template>
    <el-dialog class="prize-add-dialog" :title="title" v-model="visible">
        <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
            <el-row>
                <el-col>
                    <el-form-item label="奖品名称" prop="awardName">
                        <el-input
                            v-model="form.awardName"
                            maxlength="10"
                            show-word-limit
                            placeholder="请填写奖品名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-form-item label="奖品类型" prop="awardType">
                        <el-radio-group v-model="form.awardType" @change="handleAwardTypeChange">
                            <el-radio :label="1">商品</el-radio>
                            <el-radio :label="2">优惠券</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <!-- todo:发货方式 -->
                <el-col v-if="form.awardType == 1">
                    <el-form-item label="发货方式">
                        <el-radio-group v-model="form.sendAwardMethod" @change="handleSendAwardMethodChange">
                            <el-radio :label="2">商家发货</el-radio>
                            <el-radio :label="3">用户自提</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <!-- todo: 优惠券 -->
                <el-col v-if="form.awardType == 2">
                    <el-form-item label="优惠券" prop="couponId">
                        <ZwChooseCoupon
                            :shopId="shopId"
                            :value="form.couponId"
                            @handle-confirm="handleConfirmCouponId"
                            :isShowName="true">
                        </ZwChooseCoupon>
                    </el-form-item>
                </el-col>
                <!-- todo: 用户自提地址 -->
                <el-col v-if="form.awardType == 1 && form.sendAwardMethod == 3">
                    <el-form-item label="自提地址" prop="address">
                        <el-input
                            v-model="form.address"
                            type="textarea"
                            maxlength="100"
                            show-word-limit
                            placeholder="请填写自提地址"
                            resize="none"
                            :rows="4"></el-input>
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-form-item label="奖品数量" prop="awardSurplusNum">
                        <el-input-number
                            v-model="form.awardSurplusNum"
                            :min="1"
                            :precision="0"
                            :controls="false"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col>
                    <el-form-item label="转盘图片" prop="awardImg">
                        <ImgUpload
                            v-if="visible"
                            ref="prizeImgRef"
                            v-model="form.awardImg"
                            :is-change="true"
                            :currentImg="currentImg"
                            @img-state-change="clearValidate('awardImg')"
                            tip-content="建议尺寸100*100，不超过1M，支持jpg、png、jpeg" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleVisible()">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, unref } from 'vue';
import { cloneDeep, isNotEmpty } from '@/commons/utils';
// import CouponDialog from './couponDialog.vue';
import ImgUpload from '@/components/ImgUpload.vue';
import defaultImg from '@/assets/imgs/mall/marketing/not-lucky-share.png';
import { ElMessage } from 'element-plus';
import storage from '@/commons/storage';
import request from '@/request/index';

let form = reactive({
    awardName: '', //奖品名称
    awardType: 1, //1商品 2优惠券 3谢谢回顾
    awardRelation: null, //奖品和九宫格的关联(前端生成正整数保证不重复)
    sendAwardMethod: 2, //1 自动发放 2商家发货 3用户自提
    address: '', //用户自提地址
    awardSurplusNum: 1, //奖品数量
    awardImg: 'default', //奖品图片
    couponId: null, //优惠券ID
    isDefault: 1 //1是正常奖品 2 是谢谢回顾奖品
});
const baseForm = cloneDeep(form);
let visible = ref(false);
const formRef = ref();
const prizeImgRef = ref();
const emit = defineEmits(['handle-confirm']);

const title = computed(() => {
    return `${form.awardRelation ? '编辑' : '添加'}奖品`;
});
const rules = computed(() => {
    const baseRuleList = {
        awardName: [
            { required: true, message: '请输入奖品名称', trigger: 'blur' },
            { max: 10, message: '最长不超过10个字', trigger: 'blur' }
        ],
        awardType: [{ required: true, trigger: 'change', message: '请选择奖品类型' }],
        sendAwardMethod: [{ required: true, trigger: 'change', message: '请选择发货方式' }],
        couponId: [{ required: true, trigger: 'change', message: '请选择优惠券' }],
        address: [
            { required: true, message: '请填写自提地址', trigger: 'blur' },
            { max: 100, message: '最长不超过100个字', trigger: 'blur' }
        ],
        awardSurplusNum: [{ required: true, message: '请输入奖品数量', trigger: 'blur' }],
        awardImg: [{ required: true, trigger: 'change', message: '请选择转盘图片' }]
    };
    return { ...baseRuleList };
});
const currentImg = computed(() => {
    return getCurrentImg(form.awardImg);
});

const handleAwardTypeChange = val => {
    if (val == 1) {
        form.couponId = null;
        form.sendAwardMethod = 2;
    } else {
        form.sendAwardMethod = 1;
        form.address = null;
    }
};
const handleSendAwardMethodChange = val => {
    if (val == 2) {
        form.address = null;
    }
};
const getImgSrc = img => {
    return img?.[0]?.response?.data?.url || defaultImg;
};
const handleConfirmCouponId = row => {
    form.couponId = row?.id;
    clearValidate('couponId');
};
let shopId = ref(0);
const handleDialog = async (row = {}) => {
    shopId.value = storage.get('ZW-SHOPID');
    Object.keys(baseForm).forEach(key => {
        form[key] = baseForm[key];
    });
    Object.assign(form, cloneDeep(row));
    handleVisible(true);
};

const getCurrentImg = val => {
    if (val?.[0]?.response?.data?.url) {
        return val?.[0]?.response?.data?.url;
    }
    if (!val) {
        return defaultImg;
    }
    if (val === 'default') {
        return defaultImg;
    }
    return val;
};

const handleVisible = (isVisible = false) => {
    visible.value = isVisible;
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const handleConfirm = async () => {
    if (prizeImgRef.value.loading) {
        return ElMessage({
            type: 'error',
            message: '图片正在上传中...，请稍后确认'
        });
    }
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            // todo:新增or编辑
            emit('handle-confirm', cloneDeep(form), form.awardRelation ? 'edit' : 'add');
            handleVisible(false);
        }
    });
};

defineExpose({
    handleDialog
});
</script>

<style lang="scss">
.prize-add-dialog {
    max-width: 600px;
    min-width: 600px;
    .el-input,
    .el-textarea {
        max-width: 320px !important;
    }
    .img-uploader .img-uploader-icon,
    .has-upload-img {
        width: 80px !important;
        height: 80px !important;
    }
}
</style>
<style lang="scss" scoped>
.prize-add-dialog {
}
</style>
